import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Form, Button, Picker, List, Toast } from "antd-mobile";
import { ExclamationTriangleOutline } from "antd-mobile-icons";
import { createAction } from "@common/utils";
import { getWarehouseCandidates } from "@store/user-profile/selectors";
import {
  SAGA_USER_PROFILE_INIT_LOAD_DEFAULT_SCENARIO,
  SAGA_USER_PROFILE_ADD_DEFAULT_WAREHOUSE,
  SAGA_USER_PROFILE_DEL_DEFAULT_WAREHOUSE,
} from "@store/user-profile/saga-types";

const DefaultScenario = () => {
  const dispatch = useDispatch();
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);
  const warehouseItems = useSelector((state) => getWarehouseCandidates(state));
  const selectedWarehouses = useSelector(
    (state) => state.userProfile.defaultScenario
  );

  useEffect(() => {
    dispatch(createAction(SAGA_USER_PROFILE_INIT_LOAD_DEFAULT_SCENARIO));
  }, []);

  const addWarehouse = (val) => {
    dispatch(
      createAction(SAGA_USER_PROFILE_ADD_DEFAULT_WAREHOUSE, {
        id: val[0],
        callback: () =>
          Toast.show({
            icon: "success",
            content: "添加成功",
            maskClickable: false,
          }),
      })
    );
  };

  const handleDel = (record) => {
    if (selectedWarehouses.length === 1) {
      Toast.show({
        icon: <ExclamationTriangleOutline />,
        content: "至少保留1项",
        maskClickable: false,
      });
      return;
    }
    dispatch(
      createAction(SAGA_USER_PROFILE_DEL_DEFAULT_WAREHOUSE, {
        id: record.id,
        callback: () =>
          Toast.show({
            icon: "success",
            content: "删除成功",
            maskClickable: false,
          }),
      })
    );
  };

  return (
    <>
      <Form form={form}>
        <Form.Header>默认使用场景</Form.Header>
        <Form.Item
          label="所在仓库"
          extra={
            <Button
              size="small"
              color="primary"
              fill="outline"
              onClick={() => setVisible(true)}
            >
              选择
            </Button>
          }
        ></Form.Item>
        <List>
          {selectedWarehouses?.map((record, idx) => (
            <List.Item
              key={idx}
              arrow={
                <Button
                  size="small"
                  color="danger"
                  onClick={() => handleDel(record)}
                >
                  删除
                </Button>
              }
            >
              {record.name}
            </List.Item>
          ))}
        </List>
      </Form>
      <Picker
        columns={warehouseItems}
        visible={visible}
        onClose={() => {
          setVisible(false);
        }}
        onConfirm={(val) => addWarehouse(val)}
      />
    </>
  );
};

export default DefaultScenario;
